package org.thesis.mailControl;

import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.thesis.doituong.OneMail;
import org.thesis.doituong.sender;


import android.util.Log;
public class GmailControl {
	String tag = "GMAIL";
	OneMail om;

	private String username;
	private String password;
	static final String HOSTSEND = "smtp.gmail.com";// 587
	static final String HOSTGET = "imap.gmail.com";// 993
	//static final int SPORT = 587;
	//
	int n_newmail;

	public int getN_newmail() {
		return n_newmail;
	}

	public void setN_newmail(int n_newmail) {
		this.n_newmail = n_newmail;
	}

	public GmailControl(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	
	public Message[] getmail() 
	{
		Message[] message = null;

		Properties props2 = System.getProperties();
//		props2.setProperty("mail.debug", "true");

		props2.setProperty("mail.store.protocol", "imaps");
		// I used imaps protocol here

		Session session2 = Session.getInstance(props2, null);

		try {

			Store store = session2.getStore("imaps");

			store.connect(HOSTGET, username,password);
					
			
			Folder folder = store.getFolder("INBOX");// get inbox

			folder.open(Folder.READ_WRITE);// open folder can read and write;

			message = folder.getMessages();
			

		
			Log.v(tag, "lay mail xong");

		} catch (Exception e) {
			// TODO: handle exception
			Log.i(tag, "Loi get GMAIL mail");
		}
		return message;
	}
	
	//
	 public boolean check_connect() // kiem tra ket noi den server mail
     {
             Log.v(tag, "check_connect...");
                     Properties props = System.getProperties();
                     props.setProperty("mail.store.protocol", "imaps");
                     try 
                     {
//                           props.put("mail.debug", "true");
                             Session session = Session.getDefaultInstance(props, null);
                             Store store = session.getStore("imaps");
                             store.connect(HOSTGET,username, password);
                 
                 //lay so mail chua doc
                 Folder inbox = store.getFolder("Inbox");
                             inbox.open(Folder.READ_ONLY);
                             setN_newmail(inbox.getUnreadMessageCount());
                             Log.v(tag, "mail " +username + " chua doc: " + String.valueOf(inbox.getUnreadMessageCount())
                                             + "--ton mail: " +String.valueOf(inbox.getMessageCount()));
                             inbox.close(true);
                 return true;
                     
                     
             }catch (Exception e) 
             {
                     // TODO: handle exception
                     Log.v(tag, "ko the ket noi" +e.toString());
                     return false;
                     
             }
     }

	public void send2(String subject, String messbody, String toAddress, String[] attachURL) {


		try{
			
			Authenticator authenticator=null;

			// Configure your JavaMail.
			Properties props = new Properties();
//			props.setProperty("mail.debug", "true");
			props.setProperty("mail.transport.protocol", "smtps");
			// We need TTLS, which gmail requires
			props.setProperty("mail.smtp.starttls.enable","true");
			props.setProperty("mail.smtp.host", HOSTSEND);
			props.setProperty("mail.smtp.port", "587");
			props.setProperty("mail.smtps.auth", "true");
			authenticator = new Authenticator() {

				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					// TODO Auto-generated method stub
					return new PasswordAuthentication(username,password);
				}
				
			};


			Session session = Session.getInstance(props, authenticator);
			
			MimeMessage message1 = new MimeMessage(session);

	        message1.setFrom(new InternetAddress(username));

	        message1.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
	        
	        message1.setSubject(subject);

	        MimeBodyPart messagebodypart = new MimeBodyPart();
			messagebodypart.setText(messbody);
			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messagebodypart);
			
			for(int i=0;i<attachURL.length;i++)
				if(!attachURL[i].equalsIgnoreCase("")){
					messagebodypart = new MimeBodyPart();
					DataSource source = new FileDataSource(attachURL[i]);
					messagebodypart.setDataHandler(new DataHandler(source));
					messagebodypart.setFileName(attachURL[i]);
					multipart.addBodyPart(messagebodypart);
				}
			
			message1.setContent(multipart);

			Transport transport = session.getTransport("smtp");
			transport.connect(HOSTSEND,587, username, password);
			transport.sendMessage(message1, message1.getAllRecipients());
			transport.close();
			
			Log.i(tag, "send GMAIL thanh cong...");
		} catch (Exception e) {
			// TODO: handle exception
			Log.i(tag, "Loi gui GMAIL");
		}
	}
	
	public void send(sender sd)
	{
		String subject = sd.getSub();
		String messbody = sd.getMesbody();
		List<String>list_Recipients = sd.getList_to();
		List<String>list_file_send = sd.getList_file_attach();
		
		try
		{
			Authenticator authenticator=null;

			// Configure your JavaMail.
			Properties props = new Properties();
//			props.setProperty("mail.debug", "true");
			props.setProperty("mail.transport.protocol", "smtps");
			// We need TTLS, which gmail requires
			props.setProperty("mail.smtp.starttls.enable","true");
			props.setProperty("mail.smtp.host", HOSTSEND);
			props.setProperty("mail.smtp.port", "587");
			props.setProperty("mail.smtps.auth", "true");
			authenticator = new Authenticator() {

				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					// TODO Auto-generated method stub
					return new PasswordAuthentication(username,password);
				}
				
			};


			Session session = Session.getInstance(props, authenticator);
			
			MimeMessage message1 = new MimeMessage(session);

	        message1.setFrom(new InternetAddress(username));
	        
	        //mang dia chi gui di duoc lay tu list
	        InternetAddress InAdd[] = new InternetAddress[list_Recipients.size()];
            for (int i = 0; i < list_Recipients.size(); i ++)
            {
                    InAdd[i] = new InternetAddress(list_Recipients.get(i).toString());
                    Log.v(subject, "gui toi : " + list_Recipients.get(i).toString());
            }
	        message1.addRecipients(Message.RecipientType.TO, InAdd);
	        
	        message1.setSubject(subject);

	        MimeBodyPart messagebodypart = new MimeBodyPart();
			messagebodypart.setText(messbody);
			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messagebodypart);
			for(int i = 0; i < list_file_send.size(); i ++)
			{
				String str_file_att = list_file_send.get(i).toString();
				Log.v(messbody, str_file_att);
				if(!str_file_att.equals(""))
				{
					messagebodypart = new MimeBodyPart();
					DataSource source = new FileDataSource(str_file_att);
					messagebodypart.setDataHandler(new DataHandler(source));
					messagebodypart.setFileName(str_file_att);
					multipart.addBodyPart(messagebodypart);
				}
			}
			
			message1.setContent(multipart);

			Transport transport = session.getTransport("smtp");
			transport.connect(HOSTSEND,587, username, password);
			transport.sendMessage(message1, message1.getAllRecipients());
			transport.close();
			
			Log.i(tag, "send GMAIL thanh cong...");
		}
		catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi send" + e.toString());
		}
	}
}
